package com.uniview.service.orderType.impl;

import java.math.BigDecimal;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.uniview.entity.vo.Pager;
import com.uniview.entity.vo.orderType.ProjectDelivery;
import com.uniview.plugins.adapter.OLDataSource;
import com.uniview.service.orderType.ProjectDeliveryService;

@Service("projectDeliveryService")
public class ProjectDeliveryServiceImpl implements ProjectDeliveryService {
	
	
	@Value("#{configProperties['uniview.ProjectDelivery']}")
	private String projectDeliveryTable;
	
	@Autowired
	private OLDataSource olDataSource;

	@Override
	public Pager<ProjectDelivery> findProjectDeliveryByWorkNo(String workNo,String queryString, int page, int limit) throws Exception {
		workNo = workNo.toUpperCase();
		StringBuilder builder = new StringBuilder();
		builder.append("select * from (select A.*,ROWNUM as id FROM ( ");
		builder.append("select * from "+projectDeliveryTable+ " where UPPER(\"account\") = '"+workNo+"'" );
		
		if(StringUtils.isNotBlank(queryString)){
			builder.append(" and (\"projectName\" like '%" + queryString + "%' or \"ContactPerson\" like '%"+queryString+"%' or \"ContactAddress\" like '%"+queryString+"%') ");
		}
		builder.append(" ) A WHERE ROWNUM <= " + page + " * " + limit + " ) WHERE id > (" + page + " - 1) *" + limit);
		String countSql="select count(*) from "+projectDeliveryTable+ " where UPPER(\"account\") = '"+workNo+"' ";
		if(StringUtils.isNotBlank(queryString)){
			countSql += "and (\"projectName\" like '%" + queryString + "%' or \"ContactPerson\" like '%"+queryString+"%' or \"ContactAddress\" like '%"+queryString+"%') ";
		}
		List<ProjectDelivery> list =olDataSource.queryForList(ProjectDelivery.class, builder.toString());
		int total =olDataSource.getCount(countSql);
		Pager<ProjectDelivery> pager = new  Pager<ProjectDelivery> ();
		pager.setPagerList(list);
		pager.setTotalRow(total);
		return pager;
	}

	@Override
	public Integer findProjectIdByProjectNo(String projectNo) throws Exception {
		String sql = "select \"projectId\" from " + projectDeliveryTable + " where upper(\"projectNo\") = upper('" + projectNo + "')";
		BigDecimal big = (BigDecimal)olDataSource.queryForObject(sql, 1);
		return big.intValue();
	}
	
	

}
